package com.quasar.hpatient.view;

import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.model.custommodel.InspactionBean;
import com.quasar.hpatient.model.custommodel.TemperatureTableItem;
import com.quasar.hpatient.model.medicalmodel.AssayLinData;
import com.quasar.hpatient.model.medicalmodel.SevenDayInspectionData;
import com.quasar.hpatient.onInterface.viewInterface.UiInterface;
import com.quasar.hpatient.presenter.SevenDayInspectionPresenter;
import com.quasar.hpatient.utils.DateUtil;
import com.quasar.hpatient.view.adapter.AssayLinAdapter;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import lecho.lib.hellocharts.formatter.SimpleLineChartValueFormatter;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

@EActivity(R.layout.activity_assay_lin)
public class AssayLinActivity extends BaseActivity implements UiInterface<SevenDayInspectionData> {

    @ViewById(R.id.line_chart)
    LineChartView lineChart;  //折线图
    @ViewById(R.id.fl_visibili)
    FrameLayout fl_visibili;


    @Extra
    String ItemName;  //化验单名称
    @Extra
    String ItemTime;   //化验单事件

    private SevenDayInspectionPresenter assayLinPresenter;
    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<PointValue> mPointValues1 = new ArrayList<PointValue>();
    private List<PointValue> mPointValues2 = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();

    List<String> a = new ArrayList<>();  //
    List<String> y = new ArrayList<>();
    String[] date = {"1"};// X轴的标注
    int[] score = {74};// 图表的数据.


    Float MAXValue, MIXValue;
    int Status;

    @Extra
    InspactionBean inspactionBean;
    /**
     * 0 代表无参考值
     * 1 代表只有最小值
     * 2 代表只有最大值
     * 3 代表有最大最小值
     */

    int Maxstatus = 2;
    int Mixstatus = 1;
    int Nostatus = 0;
    int Allstatus = 3;

    //化验单显示列表
    private AssayLinAdapter assayLinAdapter;
    @ViewById(R.id.rv_jpsh_msg)
    RecyclerView rv_jpsh_msg;
    private View errorView;
    @ViewById(R.id.ll_visibili)
    LinearLayout ll_visibili;
    public void initRecyclerView(){
        errorView = getLayoutInflater().inflate(R.layout.assaylin_medicine, (ViewGroup) rv_jpsh_msg.getParent(), false);

        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("值");
        if(inspactionBean!=null){
            if(inspactionBean.getInspactionitemBeen()!=null){
                if(inspactionBean.getInspactionitemBeen().getDoseName()!=null && inspactionBean.getInspactionitemBeen().getDoseName().length()>0){
                    stringBuffer.append("("+inspactionBean.getInspactionitemBeen().getDoseName()+")");
                }
            }
        }
        TextView tv_val= (TextView) errorView.findViewById(R.id.tv_val);
        tv_val.append(stringBuffer.toString());

        rv_jpsh_msg.setLayoutManager(new LinearLayoutManager(this));
        rv_jpsh_msg.setHasFixedSize(true);
        rv_jpsh_msg.setNestedScrollingEnabled(false);
    }
    public void initAdapter(){
        assayLinAdapter=new AssayLinAdapter();
        rv_jpsh_msg.setAdapter(assayLinAdapter);
    }


    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;

    @AfterViews
    void init() {
        if(ItemName!=null){
            main_toolbar.setTitle(ItemName);
        }
        initView();
        initRecyclerView();
        initAdapter();
        initData();
    }

    @Override
    protected void initView() {
        initToolbar();
        assayLinPresenter = new SevenDayInspectionPresenter(this);
    }

    @Override
    protected void initData() {

        if (ItemTime != null) {
            if (ItemName != null) {
                assayLinPresenter.getSevenDayInspection(ItemTime, ItemName,statsType);
            }
        }
    }

    String statsType="7";


    public void broken_line(int status) {

        if (status == Maxstatus) {
            getAxisXLables();// 获取x轴的标注
            getAxisPoints();// 获取坐标点
            getAxisPointMax(MAXValue);  //最大值
            if (mPointValues.size() == 0) {
                fl_visibili.setVisibility(View.VISIBLE);
                ll_visibili.setVisibility(View.GONE);
            } else {
                initLineChart();// 初始化
            }

        } else if (status == Mixstatus) {
            getAxisXLables();// 获取x轴的标注
            getAxisPoints();// 获取坐标点
            getAxisPointMix(MIXValue);      //最小值
            if (mPointValues.size() == 0) {
                fl_visibili.setVisibility(View.VISIBLE);
                ll_visibili.setVisibility(View.GONE);
            } else {
                initLineChart();// 初始化
            }
        } else if (status == Allstatus) {
            getAxisXLables();// 获取x轴的标注
            getAxisPoints();// 获取坐标点
            getAxisPointMix(MAXValue);      //最小值
            getAxisPointMax(MIXValue);  //最大值
            if (mPointValues.size() == 0) {
                fl_visibili.setVisibility(View.VISIBLE);
                ll_visibili.setVisibility(View.GONE);
            } else {
                initLineChart();// 初始化
            }
        } else if (status == Nostatus) {
            fl_visibili.setVisibility(View.VISIBLE);
            ll_visibili.setVisibility(View.GONE);
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        mPointValues.clear();
        mPointValues1.clear();
        mAxisXValues.clear();
        mPointValues2.clear();

        if (a != null) {
            a.clear();
        }
        if (y != null) {
            y.clear();
        }
    }

    String timedaylity = "";

    @Override
    public void onViewSuccess(SevenDayInspectionData data) {


        Collections.sort(data.getList(), new Comparator<SevenDayInspectionData.ListBean>() {
            @Override
            public int compare(SevenDayInspectionData.ListBean o1, SevenDayInspectionData.ListBean o2) {
                if (o1.getInspectionIndex().getTestTime() != null && o2.getInspectionIndex().getTestTime() != null) {
                    Date date1 = DateUtil.stringToDatess(o1.getInspectionIndex().getTestTime());
                    Date date2 = DateUtil.stringToDatess(o2.getInspectionIndex().getTestTime());
                    if (date1.after(date2)) {
                        return 1;
                    }
                }
                return -1;
            }
        });

        if (data.getList() != null && data.getList().size() > 0) {
            if (isstauts == 1) {
                timedaylity = data.getList().get(data.getList().size() - 1).getInspectionIndex().getTestTime().substring(0, 10);
            } else if (isstauts == 2) {
                timedaylity = data.getList().get(0).getInspectionIndex().getTestTime().substring(0, 10);
            }
        }

        if (data != null) {
            if (data.getList().size() != 0) {
                for (int i = 0; i < data.getList().size(); i++) {

                    data.getList().get(i).Judgereference("<0.01");
                    if (data.getList().get(i).getMaxValue() != 0) {
                        MAXValue = data.getList().get(i).getMaxValue();//获取参考值最大值
                        data.getList().get(i).getStatus();
                    }
                    if (data.getList().get(i).getMixValue() != 0) {
                        MIXValue = data.getList().get(i).getMixValue(); //获取参考值最小值
                    }
                    Status = data.getList().get(i).getStatus();
                    String time = data.getList().get(i).getInspectionIndex().getTestTime().substring(5, 10);
                    a.add(time);
                    y.add(data.getList().get(i).getItemValue());


                }
            }
            broken_line(Status); //折线处理
        }


        List<AssayLinData> assayLinData=new ArrayList<>();

        for (int i=0;i<data.getList().size();i++){
            SevenDayInspectionData.ListBean listBean=data.getList().get(i);
            AssayLinData assayLinData1=new AssayLinData();
            //判断如果检测值为空或者长度为0则不加
            if(listBean.getItemValue()==null || listBean.getItemValue().length()==0){
                continue;
            }
            assayLinData1.setItemName(listBean.getItemName());
            assayLinData1.setItemValue(listBean.getItemValue());
            assayLinData1.setStandardValue(listBean.getStandardValue());
            assayLinData1.setCreatTime(listBean.getInspectionIndex().getTestTime());
            assayLinData.add(assayLinData1);
        }

        Collections.sort(assayLinData, new Comparator<AssayLinData>() {
            @Override
            public int compare(AssayLinData o1, AssayLinData o2) {
                if (o1.getCreatTime() != null && o2.getCreatTime() != null) {
                    Date date1 = DateUtil.stringToDatess(o1.getCreatTime());
                    Date date2 = DateUtil.stringToDatess(o2.getCreatTime());
                    if (date1.before(date2)) {
                        return 1;
                    }
                }
                return -1;
            }
        });

        assayLinAdapter.setNewData(assayLinData);
        assayLinAdapter.removeHeaderView(errorView);
        if(assayLinData.size()>0){
            assayLinAdapter.addHeaderView(errorView);
        }
    }

    @Override
    public void onViewError(String msg) {
        msg(msg);
    }

    @Override
    public void onViewRefreshUI() {

    }

    /**
     * 初始化LineChart的一些设置
     */
    private void initLineChart() {
        Line line = new Line(mPointValues).setColor(Color.parseColor("#01B786")); // 折线的颜色
        Line line1 = new Line(mPointValues1).setColor(Color.parseColor("#00000000")); // 折线的颜色
        Line line2 = new Line(mPointValues2).setColor(Color.parseColor("#00000000"));
        List<Line> lines = new ArrayList<Line>();
        line.setShape(ValueShape.CIRCLE);// 折线图上每个数据点的形状 这里是圆形 （有三种
        line.setCubic(false);// 曲线是否平滑
        line.setStrokeWidth(3);//线条的粗细，默认是3
        line.setFilled(false);// 是否填充曲线的面积
        line.setHasLabels(true);// 曲线的数据坐标是否加上备注
        line.setFormatter(new SimpleLineChartValueFormatter(3));//小数的精度
//        line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);// 是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);// 是否显示圆点 如果为false 则没有原点只有点显示

        line1.setShape(ValueShape.CIRCLE);// 折线图上每个数据点的形状 这里是圆形 （有三种
        // ：ValueShape.SQUARE
        // ValueShape.CIRCLE
        // ValueShape.SQUARE）
        line1.setStrokeWidth(3);//线条的粗细，默认是3
        line1.setCubic(false);
        line1.setFilled(false);
        line1.setHasLabels(false);
        line1.setHasLines(true);
        line1.setHasPoints(false);


        line2.setShape(ValueShape.CIRCLE);// 折线图上每个数据点的形状 这里是圆形 （有三种
        // ：ValueShape.SQUARE
        // ValueShape.CIRCLE
        // ValueShape.SQUARE）
        line2.setStrokeWidth(3);//线条的粗细，默认是3
        line2.setCubic(false);
        line2.setFilled(false);
        line2.setHasLabels(false);
        line2.setHasLines(true);
        line2.setHasPoints(false);
        lines.add(line);
        lines.add(line1);
        lines.add(line2);
        LineChartData data = new LineChartData();
        data.setLines(lines);


        //显示折线图上值的背景
        data.setValueLabelBackgroundColor(R.color.common_bottom_bar_selected_bg);
        data.setValueLabelBackgroundEnabled(false);
        data.setValueLabelsTextColor(Color.parseColor("#4A8A00"));

        // 坐标轴
        Axis axisX = new Axis(); // X轴
        axisX.setHasTiltedLabels(false); // X轴下面坐标轴字体是斜的显示还是直的，true是斜的显示
        // axisX.setTextColor(Color.WHITE); //设置字体颜色
        axisX.setTextColor(Color.parseColor("#000000"));// 灰色

        // axisX.setName("未来几天的天气"); //表格名称
        axisX.setTextSize(11);// 设置字体大小
        axisX.setMaxLabelChars(7); // 最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisValues.length
        axisX.setValues(mAxisXValues); // 填充X轴的坐标名称
        data.setAxisXBottom(axisX); // x 轴在底部
        // data.setAxisXTop(axisX); //x 轴在顶部
        axisX.setHasLines(true); // x 轴分割线

        Axis axisY = new Axis(); // Y轴
        axisY.setName("");// y轴标注
        axisY.setTextSize(11);// 设置字体大小
        axisY.setTextColor(Color.parseColor("#000000"));
        data.setAxisYLeft(axisY); // Y轴设置在左边

        // data.setAxisYRight(axisY); //y轴设置在右边
        // 设置行为属性，支持缩放、滑动以及平移
        lineChart.setInteractive(true);
        lineChart.setZoomType(ZoomType.HORIZONTAL); // 缩放类型，水平
        lineChart.setMaxZoom((float) 3);// 缩放比例
        lineChart.setLineChartData(data);
        lineChart.setVisibility(View.VISIBLE);

        Viewport v = new Viewport(lineChart.getMaximumViewport());
        v.left = 0;
        v.right = 7;
        lineChart.setCurrentViewport(v);
        lineChart.setOnTouchListener(touchListener());
    }

    /**
     * X 轴的显示
     */
    private void getAxisXLables() {
        for (int i = 0; i < a.size(); i++) {
            mAxisXValues.add(new AxisValue(i).setLabel(a.get(i)));
        }
    }

    /**
     * 图表的每个点的显示
     */
    private void getAxisPoints() {
        for (int i = 0; i < y.size(); i++) {
            if (y.get(i) != null && y.get(i) != "") {
                mPointValues.add(new PointValue(i, Float.parseFloat(y.get(i))));
            }
        }
    }

    /**
     * 区间范围
     */

    List<Float> mixValue = new ArrayList<>();
    List<Float> maxValue = new ArrayList<>();

    private void getAxisPointMix(Float mixvalue) {   //最小值

        //添加最小值
        for (int i = 0; i < 7; i++) {
            mixValue.add(Float.valueOf(mixvalue));
        }

        Float[] score1 = new Float[mixValue.size()];
        for (int i = 0; i < mixValue.size(); i++) {
            score1[i] = mixValue.get(i);
        }
        for (int i = 0; i < score1.length; i++) {
            mPointValues1.add(new PointValue(i, score1[i]));
        }
    }

    private void getAxisPointMax(Float maxvalue) {   //最大值

        //添加最大值
        for (int i = 0; i < 7; i++) {
            maxValue.add(Float.valueOf(maxvalue));
        }
        Float[] score2 = new Float[maxValue.size()];
        for (int i = 0; i < maxValue.size(); i++) {
            score2[i] = maxValue.get(i);
        }
        for (int i = 0; i < score2.length; i++) {
            mPointValues2.add(new PointValue(i, score2[i]));
        }
    }


    public View.OnTouchListener touchListener() {
        View.OnTouchListener touchListener = new View.OnTouchListener() {
            float ratio = 1.8f; //水平和竖直方向滑动的灵敏度,偏大是水平方向灵敏
            float x0 = 0f;
            float y0 = 0f;


            float x_src = 0f;
            float y_src = 0f;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        x0 = event.getX();
                        y0 = event.getY();
                        x_src = event.getX();
                        y_src = event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        float dx = Math.abs(event.getX() - x_src);
                        float dy = Math.abs(event.getY() - y_src);
                        if (event.getX() - x_src > 50) {
//                            向左滑动
                            mPointValues.clear();
                            mPointValues1.clear();
                            mAxisXValues.clear();
                            mPointValues2.clear();
                            a.clear();
                            y.clear();
                            isstauts = 1;
                            assayLinPresenter.getSevenDayInspection(timedaylity, ItemName,"7");
                        } else if (x_src - event.getX() > 50) {
                            //  向右滑动
                            mPointValues.clear();
                            mPointValues1.clear();
                            mAxisXValues.clear();
                            mPointValues2.clear();
                            a.clear();
                            y.clear();
                            isstauts = 2;
                            assayLinPresenter.getSevenDayInspection(timedaylity, ItemName,"14");
                        }

                        break;
                    case MotionEvent.ACTION_MOVE:
                        float dxx = Math.abs(event.getX() - x0);
                        float dyx = Math.abs(event.getY() - y0);
                        x0 = event.getX();
                        y0 = event.getY();
                        break;
                }
                return false;
            }
        };

        return touchListener;
    }

    int isstauts=1;
}
